package com.djsearch.ui;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Window;
import android.widget.FrameLayout;
import android.widget.Toast;

import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.map.ItemizedOverlay;
import com.baidu.mapapi.map.LocationData;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationOverlay;
import com.baidu.mapapi.map.OverlayItem;
import com.baidu.mapapi.map.PoiOverlay;
import com.baidu.mapapi.search.MKAddrInfo;
import com.baidu.mapapi.search.MKBusLineResult;
import com.baidu.mapapi.search.MKDrivingRouteResult;
import com.baidu.mapapi.search.MKPoiInfo;
import com.baidu.mapapi.search.MKPoiResult;
import com.baidu.mapapi.search.MKSearch;
import com.baidu.mapapi.search.MKSearchListener;
import com.baidu.mapapi.search.MKSuggestionResult;
import com.baidu.mapapi.search.MKTransitRouteResult;
import com.baidu.mapapi.search.MKWalkingRouteResult;
import com.baidu.platform.comapi.basestruct.GeoPoint;
import com.djsearch.DJSearchApp;
import com.djsearch.R;
import com.djsearch.controller.JSONResp;

/**
 * @author dingzhongchang
 * @version 1.0.0
 */
public class LocInfoActivity extends BaseActivity {
	final static String TAG = "LocInfoActivity";
	static MapView mMapView = null;
	FrameLayout mMapViewContainer = null;
	MyLocationOverlay myLocationOverlay = null;
	BMapManager mBMapMan = null;
	SharedPreferences sharedata;
	/**
	 * 圆心经纬度坐标
	 */
	private double mLat = 39.90923;
	private double mLon = 116.357428;
	/**
	 * 接收传递过来的定位信息
	 */
	private double acceptLatitude;//经度 
	private double acceptLongitude;//纬度
	Intent intent;
	Bundle bundle;
	LocOverlay ov;
	private String type = "0";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getWindow().requestFeature(Window.FEATURE_NO_TITLE);
		mBMapMan = ((DJSearchApp) getApplication()).mBMapMan;
//		mBMapMan = ((DJSearchApp) getApplication()).mBMapMan ;
		setContentView(R.layout.map_view);
		intent = getIntent();
		if (intent != null) {
			bundle = intent.getExtras();
			if (bundle != null) {
			    type = bundle.getString("type");
			    if (type.equals("0")) {
			    	acceptLatitude = bundle.getDoubleArray("locinfo")[0];
				    acceptLongitude = bundle.getDoubleArray("locinfo")[1];
			    }
			}
		}
		sharedata = this.getSharedPreferences("LOC", 0);
		initView();
		initOnClick();
		initHandler();
		if (type.equals("1")) {
			setBaiduMapPoi();
		}
	}

	@Override
	protected void onStart() {
		refreshLoc();
		super.onStart();
	}

	private void refreshLoc() {
		mMapView.getOverlays().clear();
		LocationData locData = new LocationData();
		if (bundle != null && type.equals("1")) {
			locData.latitude = Double.valueOf(sharedata.getString("latitude",
				String.valueOf(mLat)));
			locData.longitude = Double.valueOf(sharedata.getString("longitude",
					String.valueOf(mLon)));
		} else if (bundle == null) {
			locData.latitude = Double.valueOf(sharedata.getString("latitude",
					String.valueOf(mLat)));
				locData.longitude = Double.valueOf(sharedata.getString("longitude",
						String.valueOf(mLon)));
		} else {
			locData.latitude = acceptLatitude;
			locData.longitude = acceptLongitude;
		}
//		
		locData.accuracy = Float
				.valueOf(sharedata.getString("accuracy", "2.0"));
		locData.direction = Float.valueOf(sharedata.getString("direction",
				"2.0"));
		myLocationOverlay.setData(locData);
		mMapView.getOverlays().add(myLocationOverlay);
//		mMapView.refresh();
		GeoPoint point = new GeoPoint((int) (locData.latitude * 1E6),
				(int) (locData.longitude * 1E6));
		mMapView.getController().setCenter(point);
		String locDetail = sharedata.getString("addr", "北京");
		OverlayItem item = new OverlayItem(point, locDetail, locDetail);
		Drawable marker = getResources().getDrawable(R.drawable.person_info_icon); // 得到需要标在地图上的资源
		// marker.setBounds(0, 0, marker.getIntrinsicWidth(),
		// marker.getIntrinsicHeight()); // 为maker定义位置和边界
		item.setMarker(marker);
		ov = new LocOverlay(marker, this);
		ov.addItem(item);
		mMapView.getOverlays().add(ov);
		mMapView.refresh();
		mMapView.getController().setCenter(point);
		
	}
	
	private void setBaiduMapPoi() {
		String whatSearch = "";
		if (type.equals("1")) {
			whatSearch = bundle.getString("search");
		}
		MKSearch mKSearch = new MKSearch();  
	    mKSearch.init(mBMapMan, new MySearchListener());  
	    mKSearch.poiSearchNearBy(whatSearch, new GeoPoint((int) (Double.valueOf(sharedata.getString("latitude",
		String.valueOf(mLat))) * 1E6),  
	    (int) (Double.valueOf(sharedata.getString("longitude",
	    String.valueOf(mLon))) * 1E6)), 5000); 
	}
	
	
	/**
	 * 显示poi信息监听类
	 * @author chenyang2
	 *
	 */
	public class MySearchListener implements MKSearchListener {  
  
        public void onGetDrivingRouteResult(MKDrivingRouteResult arg0, int arg1){
        	
        	
        }  
        public void onGetPoiResult(MKPoiResult arg0, int arg1, int arg2){  
            if (arg0 == null) {  
                return;  
            }  
//            mMapView.getOverlays().clear(); 
            PoiOverlay poioverlay = new PoiOverlay(LocInfoActivity.this, mMapView);   
            		
            // 在地图上显示PoiOverlay（将搜索到的兴趣点标注在地图上）  
            poioverlay.setData(arg0.getAllPoi());  
            // 为地图添加覆盖物  
            mMapView.getOverlays().add(poioverlay);  
           /*if (arg0.getNumPois() > 0) {  
        	   for(int i=0;i<arg0.getAllPoi().size();i++) {
        		   MKPoiInfo poiInfo = arg0.getPoi(i); 
        		   GeoPoint point = arg0.getPoi(i).pt;
        		   String locDetail = sharedata.getString("addr", "郑州");
        		   OverlayItem item = new OverlayItem(point, poiInfo.name, poiInfo.name);
        		   Drawable marker = getResources().getDrawable(R.drawable.person_info_icon); // 得到需要标在地图上的资源
        			// marker.setBounds(0, 0, marker.getIntrinsicWidth(),
        			// marker.getIntrinsicHeight()); // 为maker定义位置和边界
        		   item.setMarker(marker);
        		   ov.addItem(item);
        		   mMapView.getOverlays().add(ov);
        		   mMapView.refresh();
        	   }
        	   mMapView.getController().setCenter(arg0.getPoi(0).pt);
            } */
           mMapView.refresh();
        }  
  
        public void onGetTransitRouteResult(MKTransitRouteResult arg0, int arg1) {
        	
        }  
  
        public void onGetWalkingRouteResult(MKWalkingRouteResult arg0, int arg1) {
        	
        }

		@Override
		public void onGetAddrResult(MKAddrInfo arg0, int arg1) {
			
		}

		@Override
		public void onGetBusDetailResult(MKBusLineResult arg0, int arg1) {
			// TODO Auto-generated method stub
			
		}


		@Override
		public void onGetPoiDetailSearchResult(int arg0, int arg1) {
			// TODO Auto-generated method stub
			
		}


		@Override
		public void onGetSuggestionResult(MKSuggestionResult arg0, int arg1) {
			// TODO Auto-generated method stub
			
		}

    }  
	
	
	@Override
	protected void onPause() {
		mMapView.onPause();
//		if (mBMapMan != null) {
//			mBMapMan.stop();
//		}
		super.onPause();
	}

	@Override
	protected void onResume() {
		mMapView.onResume();
//		if (mBMapMan != null) {
//			mBMapMan.start();
//		}
		super.onResume();
		
	}

	
	
	
	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();

	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		mMapView.onSaveInstanceState(outState);

	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
		mMapView.onRestoreInstanceState(savedInstanceState);
	}

	@Override
	protected void onDestroy() {
		mMapView.destroy();
//		if (mBMapMan != null) {
//			mBMapMan.destroy();
//			mBMapMan = null;
//		}
		super.onDestroy();
	}

	@Override
	void initHandler() {
		// TODO Auto-generated method stub

	}

	@Override
	void initView() {
		mMapView = (MapView) findViewById(R.id.bmapView);
		// mMapController = mMapView.getController();
		mMapView.setLongClickable(true);
		mMapView.getController().setZoom(15);
		mMapView.getController().enableClick(true);
		mMapView.setDoubleClickZooming(true);
		mMapView.setTraffic(true);
		// mMapView.displayZoomControls(true);
		// mMapController.setMapClickEnable(true);
		// mMapView.setSatellite(false);
		myLocationOverlay = new MyLocationOverlay(mMapView);
		myLocationOverlay.enableCompass();
	}

	@Override
	void initOnClick() {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			finish();
		}
		return false;
	}

	@Override
	void getDataToResolve(JSONResp response) {
		// TODO Auto-generated method stub
		
	}

}

class LocOverlay extends ItemizedOverlay<OverlayItem> {
	private List<OverlayItem> mGeoList = new ArrayList<OverlayItem>();
	private Context mContext = null;

	// static PopupOverlay pop = null;

	public LocOverlay(Drawable marker, Context context) {
		super(marker);
		this.mContext = context;
		// pop = new PopupOverlay(LocInfoActivity.mMapView,
		// new PopupClickListener() {
		//
		// @Override
		// public void onClickedPopup() {
		// // TODO
		// }
		// });
		populate();

	}

	protected boolean onTap(int index) {
		// Drawable marker = this.mContext.getResources().getDrawable(
		// R.drawable.pop); // 得到需要标在地图上的资源
		// BitmapDrawable bd = (BitmapDrawable) marker;
		// Bitmap popbitmap = bd.getBitmap();
		// // pop.showPopup(popbitmap, mGeoList.get(index).getPoint(), 32);
		Toast.makeText(this.mContext, mGeoList.get(index).getTitle(),
				5000).show();
		super.onTap(index);
		return false;
	}

	
//	public boolean onTap(GeoPoint pt, MapView mapView) {
//		// if (pop != null) {
//		// pop.hidePop();
//		// }
//		super.onTap(pt, mapView);
//		return false;
//	}

	
	@Override
	protected OverlayItem createItem(int i) {
		return mGeoList.get(i);
	}

	@Override
	public int size() {
		return mGeoList.size();
	}

	public void addItem(OverlayItem item) {
		mGeoList.add(item);
		populate();
	}

	public void removeItem(int index) {
		mGeoList.remove(index);
		populate();
	}

}
